import React, { Component } from 'react';

class From extends Component {
  constructor() {
    super();
    this.state = {
      val1: '',
      val2: '',
      val3: '',
      val4: []
    }
  }
  componentDidMount() {
    // 给输入框赋值
    this.setState({
      val1: 666,
      val2: 777,
      val3: 'nv',
      val4: ['rap', 'sing'],
      val5: 3
    })
  }
  setVal1(e) {
    // console.log(e.target.value);
    this.setState({
      val1: e.target.value
    })
  }
  setVal2(e) {
    // console.log(e.target.value);
    this.setState({
      val2: e.target.value
    })
  }
  setVal3(e) {
    // console.log(e.target.value);
    this.setState({
      val3: e.target.value
    })
  }
  setVal4(e) {
    let item = e.target.value;
    let arr = this.state.val4;
    if(arr.includes(item)) {
      // 值为真，需要删除
      arr.splice(arr.indexOf(item), 1)
    }else {
      // 值为假，需要添加
      arr.push(e.target.value)
    }
    this.setState({
      val4: arr
    })
  }
  setVal5(e) {
    // console.log(e.target.value);
    this.setState({
      val5: e.target.value
    })
  }
  render() {
    return (
      <div>
        <p>表单控件-受控组件和非受控组件</p>
        <p>受控组件：可以通过代码控制组件的值，控制是指获取值以及设置值</p>
        <p>非受控组件：用户选择文件后，才可以通过代码获取文件</p>
        {/* value 监听数据的变化，修改视图 */}
        {/* onChange 监听视图的变化，获取数据 */}
        <input type="text" value={this.state.val1} onChange={(e)=>this.setVal1(e)}/>
        <p>输入框的值：{this.state.val1}</p>
        <textarea value={this.state.val2} onChange={(e)=>this.setVal2(e)}></textarea>
        <p>文本域的值：{this.state.val2}</p>
        <p>选择性别：</p>
        <input name="sex" type="radio" value="nan" onChange={(e)=>this.setVal3(e)}
        checked={this.state.val3 === 'nan'} />男
        <input name="sex" type="radio" value="nv" onChange={(e)=>this.setVal3(e)}
        checked={this.state.val3 === 'nv'} />女
        <input name="sex" type="radio" value="none" onChange={(e)=>this.setVal3(e)}
        checked={this.state.val3 === 'none'} />保密
        <p>你的性别：{this.state.val3}</p>
        <p>选择爱好：</p>
        <input type="checkbox" value="sing" onChange={(e)=>this.setVal4(e)} checked={this.state.val4.includes('sing')}/>唱
        <input type="checkbox" value="dance" onChange={(e)=>this.setVal4(e)} checked={this.state.val4.includes('dance')}/>跳
        <input type="checkbox" value="rap" onChange={(e)=>this.setVal4(e)} checked={this.state.val4.includes('rap')}/>rap
        <input type="checkbox" value="basketball" onChange={(e)=>this.setVal4(e)} checked={this.state.val4.includes('basketball')}/>打篮球
        <p>你的爱好：{this.state.val4.map(item => {
          return <span key={item}>{item},</span>
        })}</p>
        <p>收货地址：</p>
        <select value={this.state.val5} onChange={(e)=>this.setVal5(e)}>
          <option value="1">京</option>
          <option value="2">津</option>
          <option value="3">沪</option>
          <option value="4">渝</option>
        </select>
        <p>收货地址：{this.state.val5}</p>
      </div>
    );
  }
}

export default From;
